<template>
  <div class="event-detail-page">
    <div class="page-header">
      <n-button quaternary @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h1>事件详情</h1>
      <n-popover trigger="click" placement="bottom-end">
        <template #trigger>
          <n-button quaternary>
            <n-icon :size="20">
              <EllipsisVertical />
            </n-icon>
          </n-button>
        </template>
        <div class="action-menu">
          <div class="action-item" @click="handleActionSelect('edit')">
            <n-icon :size="16">
              <Create />
            </n-icon>
            <span>编辑</span>
          </div>
          <div class="action-item" @click="handleActionSelect('delete')">
            <n-icon :size="16">
              <Trash />
            </n-icon>
            <span>删除</span>
          </div>
        </div>
      </n-popover>
    </div>
    
    <div class="page-content">
      <n-spin :show="loading">
        <div v-if="event" class="event-detail">
          <div class="event-header">
            <div class="event-info">
              <div class="title-row">
                <div class="event-type-indicator" :style="{ backgroundColor: eventColor }"></div>
                <h2 class="event-title">{{ event.title }}</h2>
              </div>
              <div class="event-type">{{ eventType?.name }}</div>
            </div>
            <n-button
              :type="event.is_completed ? 'success' : 'default'"
              @click="toggleCompletion"
            >
              <n-icon :size="16">
                <Checkmark v-if="event.is_completed" />
                <Ellipse v-else />
              </n-icon>
              {{ event.is_completed ? '已完成' : '标记完成' }}
            </n-button>
          </div>
          
          <div class="event-content">
            <div class="info-section">
              <h3>基本信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <label>开始日期</label>
                  <span>{{ formatDate(event.start_date, 'YYYY年MM月DD日') }}</span>
                </div>
                <div v-if="event.start_time" class="info-item">
                  <label>开始时间</label>
                  <span>{{ formatTime(event.start_time) }}</span>
                </div>
                <div class="info-item">
                  <label>优先级</label>
                  <n-tag :type="getPriorityType(event.priority)">
                    {{ getPriorityLabel(event.priority) }}
                  </n-tag>
                </div>
                <div class="info-item">
                  <label>创建时间</label>
                  <span>{{ formatDate(event.created_at, 'YYYY-MM-DD HH:mm') }}</span>
                </div>
              </div>
            </div>
            
            <div v-if="event.description" class="info-section">
              <h3>描述</h3>
              <p class="description">{{ event.description }}</p>
            </div>
            
            <!-- 动态字段显示 -->
            <div v-if="hasExtraData" class="info-section">
              <h3>详细信息</h3>
              <div class="extra-data">
                <div
                  v-for="(value, key) in event.extra_data"
                  :key="key"
                  class="extra-item"
                >
                  <label>{{ getFieldLabel(key) }}</label>
                  <span>{{ formatFieldValue(key, value) }}</span>
                </div>
              </div>
            </div>

            <!-- 饮食跟踪营养统计 -->
            <div v-if="isDietTrackingEvent && dietNutritionSummary" class="info-section">
              <h3>营养统计</h3>
              <NutritionSummaryCard
                :nutrition="dietNutritionSummary"
                :other-nutrients="dietOtherNutrients"
                :show-percentage="true"
                :show-detailed="true"
                :show-chart="false"
              />
            </div>
          </div>
        </div>
        
        <div v-else class="not-found">
          <n-icon :size="64" color="#ccc">
            <Search />
          </n-icon>
          <p>事件不存在</p>
        </div>
      </n-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowBack,
  EllipsisVertical,
  Checkmark,
  Ellipse,
  Search,
  Create,
  Trash
} from '@vicons/ionicons5'
import { useEventsStore } from '@/stores/events'
import { formatDate, formatTime } from '@/utils/date'
import { calculateTotalNutrition, mergeOtherNutrients } from '@/utils/nutrition'
import NutritionSummaryCard from '@/components/NutritionSummaryCard.vue'
import type { Event, NutritionSummary } from '@/types'

const route = useRoute()
const router = useRouter()
const eventsStore = useEventsStore()

// 状态
const loading = ref(false)
const event = ref<Event | null>(null)

// 事件ID
const eventId = computed(() => Number(route.params.id))

// 事件类型
const eventType = computed(() => {
  return event.value ? eventsStore.getEventType(event.value.event_type_id) : null
})

// 事件颜色
const eventColor = computed(() => {
  return eventType.value?.color || '#2196F3'
})

// 是否有额外数据
const hasExtraData = computed(() => {
  return event.value?.extra_data && Object.keys(event.value.extra_data).length > 0
})

// 是否是饮食跟踪事件
const isDietTrackingEvent = computed(() => {
  return event.value?.event_type_id === 2 || eventType.value?.name === '饮食跟踪'
})

// 饮食跟踪营养汇总
const dietNutritionSummary = computed<NutritionSummary | null>(() => {
  if (!isDietTrackingEvent.value || !event.value?.extra_data?.foods_intake) {
    return null
  }

  const foodsIntake = event.value.extra_data.foods_intake
  if (!Array.isArray(foodsIntake) || foodsIntake.length === 0) {
    return null
  }

  try {
    return calculateTotalNutrition(foodsIntake)
  } catch (error) {
    console.error('计算营养汇总失败:', error)
    return null
  }
})

// 饮食跟踪其他营养素汇总
const dietOtherNutrients = computed(() => {
  if (!isDietTrackingEvent.value || !event.value?.extra_data?.foods_intake) {
    return []
  }

  const foodsIntake = event.value.extra_data.foods_intake
  if (!Array.isArray(foodsIntake) || foodsIntake.length === 0) {
    return []
  }

  try {
    return mergeOtherNutrients(foodsIntake)
  } catch (error) {
    console.error('计算其他营养素汇总失败:', error)
    return []
  }
})



// 获取优先级类型
const getPriorityType = (priority: string) => {
  const typeMap: Record<string, any> = {
    low: 'info',
    medium: 'warning',
    high: 'error'
  }
  return typeMap[priority] || 'default'
}

// 获取优先级标签
const getPriorityLabel = (priority: string) => {
  const labelMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return labelMap[priority] || priority
}

// 获取字段标签
const getFieldLabel = (fieldName: string) => {
  if (!eventType.value?.form_config) return fieldName
  
  const field = eventType.value.form_config.fields.find((f: any) => f.name === fieldName)
  return field?.label || fieldName
}

// 格式化字段值
const formatFieldValue = (fieldName: string, value: any) => {
  if (value === null || value === undefined) return '-'

  // 特殊处理饮食类型ID
  if ((fieldName === 'diet_type_id' || fieldName === 'diet_type') && typeof value === 'number') {
    const dietType = eventsStore.getDietType(value)
    return dietType?.name || `未知饮食类型(${value})`
  }

  // 特殊处理食物选择器字段
  if ((fieldName === 'planned_foods' || fieldName === 'actual_foods') && Array.isArray(value)) {
    if (value.length === 0) return '暂无'
    return value.map((food: any) => food.chinese_name || food.name || food).join('、')
  }

  // 特殊处理饮食跟踪数据
  if (fieldName === 'foods_intake' && typeof value === 'object') {
    let foodsIntake: any[] = []

    // 处理不同的数据结构
    if (Array.isArray(value)) {
      foodsIntake = value
    } else if (value.foods_intake && Array.isArray(value.foods_intake)) {
      foodsIntake = value.foods_intake
    }

    if (foodsIntake.length === 0) return '暂无食物记录'

    const foodList = foodsIntake.map((intake: any) => {
      const foodName = intake.food?.name_zh || intake.food?.name || '未知食物'
      const amount = intake.amount_g || 0
      const energy = intake.calculated_nutrition?.energy_kcal || 0
      return `${foodName} ${amount}g (${Math.round(energy)}千卡)`
    }).join('、')

    // 计算营养总量
    const totals = foodsIntake.reduce((sum: any, intake: any) => {
      const nutrition = intake.calculated_nutrition || {}
      return {
        energy: sum.energy + (nutrition.energy_kcal || 0),
        protein: sum.protein + (nutrition.protein_g || 0),
        carbs: sum.carbs + (nutrition.carbohydrate_g || 0),
        fat: sum.fat + (nutrition.fat_g || 0),
        fiber: sum.fiber + (nutrition.fiber_g || 0)
      }
    }, { energy: 0, protein: 0, carbs: 0, fat: 0, fiber: 0 })

    const nutritionSummary = [
      `${Math.round(totals.energy)}千卡`,
      `蛋白质${totals.protein.toFixed(1)}g`,
      `碳水${totals.carbs.toFixed(1)}g`,
      `脂肪${totals.fat.toFixed(1)}g`,
      `纤维${totals.fiber.toFixed(1)}g`
    ].join(' | ')

    return `${foodList}\n营养总量：${nutritionSummary}`
  }

  if (typeof value === 'object') return JSON.stringify(value)
  return String(value)
}

// 切换完成状态
const toggleCompletion = async () => {
  if (!event.value) return
  
  const result = await eventsStore.toggleEventCompletion(event.value.id, !event.value.is_completed)
  if (result) {
    event.value = result
  }
}

// 处理操作选择
const handleActionSelect = (key: string | number) => {
  console.log('🔧 Action selected:', key)
  switch (key) {
    case 'edit':
      router.push(`/events/${eventId.value}/edit`)
      break
    case 'delete':
      handleDelete()
      break
  }
}

// 处理删除
const handleDelete = () => {
  console.log('🗑️ 准备删除事件:', eventId.value, event.value?.title)

  window.$dialog?.warning({
    title: '确认删除',
    content: '确定要删除这个事件吗？此操作不可撤销。',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      console.log('🗑️ 用户确认删除事件:', eventId.value)
      const success = await eventsStore.deleteEvent(eventId.value)
      console.log('🗑️ 删除结果:', success)
      if (success) {
        console.log('🗑️ 删除成功，返回上一页')
        router.back()
      } else {
        console.error('🗑️ 删除失败')
      }
    }
  })
}

// 获取事件详情
const fetchEventDetail = async () => {
  loading.value = true
  try {
    // 这里应该调用API获取事件详情
    // 暂时从store中查找
    const foundEvent = eventsStore.events.find((e: any) => e.id === eventId.value)
    event.value = foundEvent as Event || null
  } catch (error) {
    console.error('Fetch event detail error:', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  await eventsStore.init()
  await fetchEventDetail()
})
</script>

<style scoped>
.event-detail-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.page-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f5f5f5;
}

.event-detail {
  max-width: 800px;
  margin: 0 auto;
}

.event-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.event-info {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.event-type-indicator {
  width: 6px;
  height: 32px;
  border-radius: 3px;
  flex-shrink: 0;
}

.event-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.event-type {
  font-size: 14px;
  color: #666;
}

.event-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-item span {
  font-size: 14px;
  color: #333;
}

.description {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
}

.extra-data {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.extra-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.extra-item:last-child {
  border-bottom: none;
}

.extra-item label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.extra-item span {
  font-size: 14px;
  color: #333;
  white-space: pre-line;
  line-height: 1.5;
}

.not-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.not-found p {
  margin-top: 16px;
  color: #666;
  font-size: 16px;
}

.action-menu {
  min-width: 120px;
  padding: 4px 0;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
  color: #333;
}

.action-item:hover {
  background-color: #f5f5f5;
}

.action-item:last-child {
  color: #d03050;
}

.action-item:last-child:hover {
  background-color: #fef2f2;
}

@media (max-width: 768px) {
  .page-header {
    padding: 12px 16px;
  }
  
  .page-content {
    padding: 16px;
  }
  
  .event-header {
    padding: 16px;
  }

  .title-row {
    gap: 8px;
  }

  .event-title {
    font-size: 20px;
  }
  
  .info-section {
    padding: 16px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
